package com.xps.and.yuntong.Ui;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jude.utils.JUtils;
import com.xps.and.yuntong.Constants;
import com.xps.and.yuntong.Data.bean1.FaceDetection;
import com.xps.and.yuntong.Data.bean1.FaceSign;
import com.xps.and.yuntong.Data.bean1.StartTrip;
import com.xps.and.yuntong.Data.net.UserNetWorks;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.AppCommond;
import com.xps.and.yuntong.Utils.TtsUtil;
import com.xps.and.yuntong.Xiangji.CameraSurfaceView;
import com.xps.and.yuntong.aly.OssService;
import com.xps.and.yuntong.aly.STSGetter;
import com.xps.and.yuntong.aly.UIDisplayer;
import com.xps.and.yuntong.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import rx.Subscriber;

/**
 * Created by administrator on 2017-12-09.
 */

public class FaceSignActivity extends BaseActivity implements View.OnClickListener, View.OnTouchListener {

    private MyReceiver receiver = null;
    private ImageView iv_fanhui, iv_right;
    private TextView tv_middle, tv_next1, tv_line_1;
    private LinearLayout ll_mianbu_next, ll_1, ll_2;
    Dialog dialog;

    private OssService ossService;
    private UIDisplayer displayer;
    //图片标记
    int successPicCount = 0;//已经成功的个数
    int actualPicCount = 0;//应该成功的个数
    private String User_Phone = "";
    private String photo_url;

    private File file;

    private String dingdan_id = "";
    /**
     * @return 以下是相机部分
     */


    private ImageButton takeBtn;
    private ImageButton xiancePhotoBtn;
    private ImageButton cameraSwitchBtn;
    private CameraSurfaceView surfaceView;
    private TextView timerTv;
    private ImageView iv1;

    private boolean isRecordVideo;
    private boolean isRecording;
    private boolean isFront;
    private String photoDir;
    private String videoDir;
    private boolean canRecordVideo;
    private boolean canTakePhoto;

    private long mRecordSeconds;
    private Timer mRecordTimer;
    private TimerTask mRecordTimerTask;
    private static final String IMAGE_UNSPECIFIED = "image/*";
    private final int IMAGE_CODE = 0;

    private void startTimer() {
        mRecordTimer = new Timer();
        mRecordTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (timerTv != null) {
                    mRecordSeconds++;
                    long second = mRecordSeconds % 60;
                    long minute = mRecordSeconds / 60;
                    final String time = String.format("%02d:%02d", minute, second);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            timerTv.setText(time);
                        }
                    });
                }
            }
        };
        mRecordTimer.schedule(mRecordTimerTask, new Date(), 1000);
        if (timerTv != null) {
            timerTv.setVisibility(View.VISIBLE);
        }
    }

    private void stopTimer() {
        if (mRecordTimer != null) {
            mRecordTimer.cancel();
            mRecordTimer = null;
            mRecordTimerTask.cancel();
            mRecordTimerTask = null;
        }
        if (timerTv != null) {
            timerTv.setText("");
            timerTv.setVisibility(View.INVISIBLE);
        }
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {

            int camera_mode = intent.getIntExtra("cameraMode", CameraSurfaceView.CameraMode_Take_Photo);
            int camera_face = intent.getIntExtra("cameraFace", Camera.CameraInfo.CAMERA_FACING_FRONT);
            photoDir = intent.getStringExtra("photoDir");
            videoDir = intent.getStringExtra("videoDir");
            canRecordVideo = intent.getBooleanExtra("recordVideo", true);
            canTakePhoto = intent.getBooleanExtra("takePhoto", true);

            if (canRecordVideo && !canTakePhoto) {
                camera_mode = CameraSurfaceView.CameraMode_Record_Video;
                xiancePhotoBtn.setVisibility(View.INVISIBLE);
                // 设置快门按钮图标--->record
                takeBtn.setImageDrawable(getResources().getDrawable(R.drawable.start_record));
            }
            if (canTakePhoto && !canRecordVideo) {
                camera_mode = CameraSurfaceView.CameraMode_Take_Photo;
                xiancePhotoBtn.setVisibility(View.INVISIBLE);
                // 设置快门按钮图标--->take photo
                takeBtn.setImageDrawable(getResources().getDrawable(R.drawable.take_photo));
            }


            if (camera_mode == CameraSurfaceView.CameraMode_Record_Video) {
                isRecordVideo = true;
            } else {
                isRecordVideo = false;
            }

            if (camera_face == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                isFront = true;
            } else {
                isFront = false;
            }

            surfaceView.initCamera(camera_mode, camera_face);
        }
    }

    private String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    @Nullable
    private String photoDirectory() {
        String dir = null;
        if (photoDir != null) {
            dir = photoDir;
        } else {
            dir = Environment.getExternalStorageDirectory().getPath() + '/' + getApplicationName() + "/photo";
        }

        File file = new File(dir);
        if (!file.exists()) {
            if (file.mkdirs()) {
                return dir;
            } else {
                return null;
            }
        }
        return dir;
    }

    @Nullable
    private String videoDirectory() {

        String dir = null;
        if (videoDir != null) {
            dir = videoDir;
        } else {
            dir = Environment.getExternalStorageDirectory().getPath() + '/' + getApplicationName() + "/video";
        }

        File file = new File(dir);
        if (!file.exists()) {
            if (file.mkdirs()) {
                return dir;
            } else {
                return null;
            }
        }
        return dir;
    }


    @Override
    protected int getLayout() {
        return R.layout.activity_regist_three;
    }

    @Override
    protected void setData() {
        displayer = new UIDisplayer(this);
        ossService = initOSS(Constants.endpoint, displayer);
    }

    @Override
    protected void init(Bundle inBundle) {
        initView();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    private void initView() {

        tv_line_1 = (TextView) findViewById(R.id.tv_line_1);
        ll_1 = (LinearLayout) findViewById(R.id.ll_1);
        ll_2 = (LinearLayout) findViewById(R.id.ll_2);
        tv_line_1.setVisibility(View.GONE);
        ll_1.setVisibility(View.GONE);
        ll_2.setVisibility(View.GONE);
        iv_fanhui = (ImageView) findViewById(R.id.iv_fanhui);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        iv_right.setVisibility(View.GONE);
        tv_middle = (TextView) findViewById(R.id.tv_middle);
        tv_middle.setText(R.string.face_recognition1);
        tv_next1 = (TextView) findViewById(R.id.tv_next1);

        ll_mianbu_next = (LinearLayout) findViewById(R.id.ll_mianbu_next);


        iv_fanhui.setOnClickListener(this);
        ll_mianbu_next.setOnClickListener(this);

        User_Phone = JUtils.getSharedPreference().getString("mobile_phone", "");
        showFaceDialog();
        dialogDismiss();
        dingdan_id = getIntent().getStringExtra("dingdan_id");


        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.xps.and.yuntong.service.RemoteService");
        registerReceiver(receiver, filter);

        /**
         * 以下是相机部分
         */

        iv1 = (ImageView) findViewById(R.id.iv1);
        Glide.with(FaceSignActivity.this).load(R.drawable.mianbu_shibie)
                .placeholder(R.mipmap.mianbu_shibie)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                .skipMemoryCache(true)
//                .bitmapTransform(new CropCircleTransformation(CameraActivity.this))
                .into(iv1);
        isFront = false;
        isRecordVideo = false;
        isRecording = false;

        surfaceView = (CameraSurfaceView) findViewById(R.id.cameraSurfaceView);

        surfaceView.editor = new CameraSurfaceView.PhotoEditor() {
            @Override
            public void editPhoto(File file, float rotate) {

                CropPictureFile(file);
            }

        };

        xiancePhotoBtn = (ImageButton) findViewById(R.id.xiancePhotoBtn);
        xiancePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intent, IMAGE_CODE);
            }
        });


        takeBtn = (ImageButton) findViewById(R.id.takePhotoBtn);

        cameraSwitchBtn = (ImageButton) findViewById(R.id.cameraSwitchBtn);
        cameraSwitchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                isFront = !isFront;
                surfaceView.switchFrontCamera(isFront);
            }
        });

        timerTv = (TextView) findViewById(R.id.timer_tv);

        init();

        cameraSwitchBtn.setOnTouchListener(this);
        takeBtn.setOnTouchListener(this);
        //   xiancePhotoBtn.setOnTouchListener(this);


    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // 按下时
            v.setAlpha(0.5f);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            // 抬起时
            v.setAlpha(1.0f);
        }

        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        stopTimer();
        surfaceView.stopPreview();
        isRecording = false;

        displayer = null;
        ossService = null;
        unRegEventBus();

        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        surfaceView.stopPreview();
        isRecording = false;
    }

    @Override
    protected void onStart() {
        super.onStart();

        surfaceView.startPreview();
        if (isRecordVideo) {
            takeBtn.setImageDrawable(getResources().getDrawable(R.drawable.start_record));
            cameraSwitchBtn.setVisibility(View.VISIBLE);
            //    xiancePhotoBtn.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        surfaceView.startPreview();
    }

    @Override
    protected void onPause() {
        super.onPause();
        surfaceView.stopPreview();
        isRecording = false;
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        surfaceView.startPreview();
        if (isRecordVideo) {
            takeBtn.setImageDrawable(getResources().getDrawable(R.drawable.start_record));
            cameraSwitchBtn.setVisibility(View.VISIBLE);
            //   xiancePhotoBtn.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 系统拍照裁剪
     **/
    private File photoFile = null;

    @Nullable
    private Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    private final static int CROP_REQUEST_CODE = 1024;

    private void CropPictureFile(File file) {
        try {
            String path = file + "";
//            URL.imgURL = path;
//            URL.RESULT_OK = 1;
            saveFile(BitmapFactory.decodeFile(String.valueOf(file), getBitmapOption(1)), "sign.jpg");
//            startActivity(new Intent(CameraActivity.this, TwoActivity.class));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CROP_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Log.d("CameraActivity", "onActivityResult: Crop Image Ok");

            } else {
                Log.d("CameraActivity", "onActivityResult: Crop Image Cancel");
                if (photoFile.exists()) {
                    photoFile.delete();
                }

            }


            photoFile = null;
        } else if (requestCode == IMAGE_CODE) {
            Bitmap bm = null;

            // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口

            ContentResolver resolver = getContentResolver();
            try {

                Uri originalUri = data.getData(); // 获得图片的uri

                bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);


                String[] proj = {MediaStore.Images.Media.DATA};

                // 好像是android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = managedQuery(originalUri, proj, null, null, null);

                // 按我个人理解 这个是获得用户选择的图片的索引值
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                // 将光标移至开头 ，这个很重要，不小心很容易引起越界
                cursor.moveToFirst();
                // 最后根据索引值获取图片路径
                String path = cursor.getString(column_index);
//                URL.imgURL = path;
//                URL.RESULT_OK = 1;
                saveFile(bm, "sign.jpg");
//                startActivity(new Intent(CameraActivity.this, TwoActivity.class));
            } catch (IOException e) {
                Log.e("TAG-->Error", e.toString());

            } finally {
                return;
            }
        }

    }

    private BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }


    public void saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + File.separator;
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        startUpload(file.getAbsolutePath());
    }


    /**
     * 以下是上传部分
     */
    //上传图片
    void startUpload(String picturePath) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String objectName = "faceSign/" + formatter.format(curDate) + "/" + User_Phone + "/sign.jpg";
        photo_url = objectName;
        SharedPreferences sp = JUtils.getSharedPreference();
        SharedPreferences.Editor spEd = sp.edit();
        spEd.putString("photo_url", objectName);
        spEd.commit();

        Log.e("111", objectName);
        ossService.asyncPutImage(objectName, picturePath, User_Phone);
        showDialogBottm();
        actualPicCount++;
    }


    public OssService initOSS(String endpoint, UIDisplayer displayer) {
        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        if (Constants.stsServer.equals("")) {
            credentialProvider = new STSGetter();
        } else {
            credentialProvider = new STSGetter(Constants.stsServer);
        }
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(this, endpoint, credentialProvider, conf);
        return new OssService(oss, Constants.bucket, displayer);
    }

    @Override
    public void photoUploadSuccess() {
        successPicCount++;

        if (successPicCount > 0 && successPicCount == actualPicCount) {
            faceSign();
        } else {
//          startUpload(file.getAbsolutePath());
        }
        Log.e("111", "已经成功的个数" + successPicCount + "应该成功的个数" + actualPicCount + "photoUploadSuccess" + "twoActivity");
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_fanhui:
//                Intent intent = new Intent(RegistThreeActivity.this, RegistFourActivity.class);
//                startActivity(intent);
                finish();
                break;

            case R.id.ll_mianbu_next:

                paiZhao();

//                startTrip();
                break;

        }
    }

    /**
     *
     */
    void paiZhao() {

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String file_name = dateFormat.format(date);

        if (isRecordVideo) {

        } else {
            String dir = photoDirectory();
            if (dir != null) {
                String tempStr = dir + "/" + file_name + ".jpg";
                file = new File(tempStr);
                Log.e("111", tempStr);
                surfaceView.takePhotoToFile(file);

            }
        }


    }

    void showDialogBottm() {
        dialog = new Dialog(this, R.style.my_dialog);
        dialog.setContentView(R.layout.dialog_progress_lan);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = JUtils.dip2px(10f); // 新位置Y坐标
        dialogWindow.setAttributes(lp);
        dialog.getWindow().setDimAmount(0);
        dialog.setCancelable(false);
        dialog.show();

    }


    void faceSign() {
        UserNetWorks.getFaceSign(photo_url, new Subscriber<FaceSign>() {
            @Override
            public void onCompleted() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                JUtils.Toast("发送失败");
            }

            @Override
            public void onNext(FaceSign faceSign) {
                if (faceSign.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(faceSign.getReturn_msg());
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    startTrip();
//                    Intent intent = new Intent(FaceSignActivity.this, DingdanKanActivity.class);
//                    startActivity(intent);
//                    finish();
                } else if (faceSign.getReturn_code().equals("FAIL")) {
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    JUtils.Toast(faceSign.getReturn_msg());
                }
            }
        });

    }


    private void startTrip() {

        Log.e("111", dingdan_id);
        UserNetWorks.startTrip(dingdan_id, new Subscriber<StartTrip>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(StartTrip startTrip) {
                Log.e("111", startTrip.getReturn_msg());
                if (startTrip.getReturn_code().equals("SUCCESS")) {
                    Intent intent = new Intent(FaceSignActivity.this, DingdanKanActivity.class);
                    startActivity(intent);
                    finish();

                }
            }
        });
    }

    public class MyReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String count = bundle.getString("count");
            TtsUtil.getInstance().startSpeaking(count + "");


//            try {
//                if (count == null) return;
//                JSONObject jsonObject = new JSONObject(count);
//                if (!TextUtils.isEmpty(jsonObject.getString("pushType"))) {
//                    TtsUtil.getInstance().startSpeaking(jsonObject.getString("pushMsg") + "");
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//            long[] pattern = {100, 400, 100, 400};   // 停止 开启 停止 开启
//            vibrator.vibrate(pattern, -1);
////            startAlarm();
//            TtsUtil.getInstance().startSpeaking("您有新的订单" + "");

        }
    }

    private void showFaceDialog() {
        android.app.AlertDialog.Builder customizeDialog =
                new android.app.AlertDialog.Builder(FaceSignActivity.this);
        final View dialogView = LayoutInflater.from(FaceSignActivity.this)
                .inflate(R.layout.dialog_dianhua, null);
        TextView textView = (TextView) dialogView.findViewById(R.id.edit_text);
        textView.setText(R.string.notifyMsg1);
        customizeDialog.setTitle("温馨提示");
        customizeDialog.setView(dialogView);
        customizeDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });

        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                });
        customizeDialog.setCancelable(false);
        customizeDialog.show();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppCommond a) {
        if (!AppCommond.check(a)) return;
        for (String activityName : a.getAcNameList()) {
            if (activityName.contains(getClass().getSimpleName())) {
                unRegEventBus();
                finish();
                break;
            }
//            if (activityName.equals(getClass().getSimpleName())) {
//                unRegEventBus();
//                finish();
//                break;
//            }
        }
    }

    void unRegEventBus() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }
}
